<?php

if (!defined('BASEPATH')) die('Access Denied.');

/**
 * µMVC Framework (c) 2011.
 * 
 * PHP5 MVC Framework software for PHP 5.2.17 or later
 * 
 * @package         µMVC
 * @filename        system/helpers/password.helper.php
 * @copyright       Lanz (c) 2011.
 * 
 */
/**
 * Password Helper Functions
 * 
 * @package         µMVC
 * @subpackage      Helper
 * @category        System
 * 
 */

if (!function_exists('comparePassword'))
{

    /**
     * compare a password to a hash
     * @param string $password the password as a plane unencrypted string
     * @param string $hash the hash to compare it with
     * @return boolean true if equal.  
     */
    function comparePassword($password, $salt, $hash)
    {
        return $hash == createPasswordHash($salt, $password);
    }
    
}

if (!function_exists('createPasswordSalt'))
{
    
    /**
     *  get a new salt - 8 hexadecimal characters long
     */
    function createPasswordSalt()
    {
        // current PHP installations should not exceed 8 characters
        // on dechex( mt_rand() )
        // but we future proof it anyway with substr()
        return substr(str_pad(dechex(mt_rand()), 8, '0', STR_PAD_LEFT), -8);
    }

}

if (!function_exists('createPasswordHash'))
{
    /**
     * Calculate the hash from a salt and a password
     * @param string $salt salt valur
     * @param string $password
     * @return string the password hash
     * @example $hash = getPasswordHash(getPasswordSalt(), $password);
     */
    function createPasswordHash($salt, $password)
    {
        return hash('whirlpool', $salt . $password);
    }
    
}

if (!function_exists('getPassKey'))
{
    /**
     * Creates a new passkey that is 20 hexadecimal values long.
     * @return type 
     */
    function getPassKey()
    {
        $key = '';
        for($i = 1; $i <= 16; $i++)
        {
            $key .= str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT);
        }
        
        return $key;
    }
}

if (!function_exists('createPassword'))
{
    /**
     * Creates a new random password.
     * @param int $len length of the password
     */
    function createPassword($len = 8)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        $password = '';
        for ($i = 0; $i < $len; $i++)
          $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        
        return $password;
    }
}
?>
